package com.lmabbe.common.mvc.interceptor;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONObject;
import com.lmabbe.common.global.constant.GlobalConstant;
import com.lmabbe.common.global.context.LmabbeSessionUser;
import com.lmabbe.common.mvc.config.LmabbeMvcProperties;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.rpc.RpcContext;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 初始化上Rpc上下文
 *
 * @author lmabbe
 * @data 2021/12/5 22:52
 */
@Component
@RequiredArgsConstructor
public class InitRpcContentInterceptor implements HandlerInterceptor {

    private final LmabbeMvcProperties lmabbeMvcProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!lmabbeMvcProperties.isPlatform() && !request.getRequestURI().contains("v3/api-docs")) {
            RpcContext.getContext()
                    .setAttachment(GlobalConstant.SYSTEM.FROM_CLIENT, request.getHeader(GlobalConstant.SYSTEM.FROM_CLIENT))
                    .setAttachment(GlobalConstant.SYSTEM.TENANT_ID, request.getHeader(GlobalConstant.SYSTEM.TENANT_ID))
                    .setAttachment(GlobalConstant.SYSTEM.AUTHORIZATION, request.getHeader(GlobalConstant.SYSTEM.AUTHORIZATION).replace(GlobalConstant.SYSTEM.AUTHENTICATION_PREFIX, ""))
                    .setAttachment(GlobalConstant.SYSTEM.LOGIN_USER, JSONObject.toJSONString(SpringUtil.getBean(LmabbeSessionUser.class).loginUser()));
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
